import mitt from 'mitt';

export const eventBus = {
  ...mitt(),
  /**
   * 请求-响应模式：发送请求并等待响应
   * @param {string} requestEvent - 请求事件名
   * @param {string} responseEvent - 响应事件名
   * @param {any} requestData - 请求数据
   * @param {number} timeout - 超时时间(毫秒)
   * @returns {Promise<any>} 响应数据
   */
  requestData(requestEvent, responseEvent, requestData, timeout = 5000) {
    return new Promise((resolve) => {
      const handler = (data) => {
        eventBus.off(responseEvent, handler)
        resolve(data)
      }
      
      eventBus.on(responseEvent, handler)
      eventBus.emit(requestEvent, requestData)
      
      setTimeout(() => {
        eventBus.off(responseEvent, handler)
        resolve(null)
      }, timeout)
    })
  },

  /**
   * 一次性监听器：监听事件一次后自动移除
   * @param {string} event - 事件名
   * @param {Function} callback - 回调函数
   * @param {number} timeout - 超时时间(毫秒)
   */
  onOnce(event, callback, timeout = 5000) {
    const handler = (data) => {
      eventBus.off(event, handler)
      callback(data)
    }
    
    eventBus.on(event, handler)
    
    if (timeout) {
      setTimeout(() => {
        eventBus.off(event, handler)
      }, timeout)
    }
  }
}